package edu.dublbo.app.habitplusfavorite.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.dublbo.app.habitplusfavorite.mapper.ResourceCatalogMapper;
import edu.dublbo.app.habitplusfavorite.model.ResourceCatalog;
import edu.dublbo.app.habitplusfavorite.service.IResourceCatalogService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 资源类别 服务实现类
 * </p>
 *
 * @author habitplus
 * @since 2021-11-29
 */
@Service
public class ResourceCatalogServiceImpl extends ServiceImpl<ResourceCatalogMapper, ResourceCatalog> implements IResourceCatalogService {

    @Override
    public List<ResourceCatalog> listOfChildren() {
        List<ResourceCatalog> resList = new ArrayList<>();
        // 获取 资源目录的数据
        List<ResourceCatalog> catalogList = baseMapper.selectList(
                Wrappers.<ResourceCatalog>lambdaQuery().orderByDesc(ResourceCatalog::getDirFlag));
        if (catalogList != null && catalogList.size() > 0) {
            Map<Integer, ResourceCatalog> idObjMap = new HashMap<>();

            // 先建立 id 到 对象的 hash 映射表
            for(ResourceCatalog c : catalogList) idObjMap.put(c.getId(), c);

            // 封装数据 -- 父子结构
            for (ResourceCatalog re: catalogList) {
                Integer key = re.getParentId();
                if (key != null && idObjMap.containsKey(key)) {
                    ResourceCatalog catalog = idObjMap.get(key);
                    if (catalog.getChildren() == null) {
                        List<ResourceCatalog> tmpList = new ArrayList<>();
                        tmpList.add(re);
                        catalog.setChildren(tmpList);
                    } else {
                        catalog.getChildren().add(re);
                    }
                    continue;
                }
                resList.add(re);
            }
        }

        return resList;
    }

}
